package com.jinwei.qunguanjia.security.handler;

import com.jinwei.qunguanjia.common.constant.Constants;
import com.jinwei.qunguanjia.common.core.domain.Response;
import com.jinwei.qunguanjia.common.utils.JsonUtils;
import com.jinwei.qunguanjia.common.utils.ServletUtils;
import com.jinwei.qunguanjia.common.utils.StringUtils;
import com.jinwei.qunguanjia.system.dto.SysLoginUser;
import com.jinwei.qunguanjia.system.service.TokenService;
import com.jinwei.qunguanjia.system.dto.SysLoginLogDTO;
import com.jinwei.qunguanjia.system.service.SysLoginLogService;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义退出处理类
 * 
 * @author yuanzs
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler
{
    @Resource
    private TokenService tokenService;

    @Resource
    private SysLoginLogService sysLoginLogService;

    /**
     * 退出处理
     *
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        SysLoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            SysLoginLogDTO sysLoginLogDTO = new SysLoginLogDTO();
            String userName = loginUser.getUsername();
            sysLoginLogDTO.setUserName(userName);
            sysLoginLogDTO.setLoginStatus(Constants.LOGOUT);
            sysLoginLogDTO.setMsg("退出成功");
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken(), userName);
            // 记录用户退出日志
            sysLoginLogService.save(sysLoginLogDTO, request);
        }
        ServletUtils.renderString(response, JsonUtils.toJsonString(Response.success()));
    }
}
